<?php

namespace App\Controller\Api;

use App\Base\BaseController4Restful;
use App\Entity\Comment;
use App\Entity\Task;
use App\Repository\TaskRepository;
use App\Service\AnnounceService;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\Routing\Annotation\Route;

class ApiTaskController extends BaseController4Restful
{
    /**
     * @Route("/api/Tasks", name="apiGetTasks",methods={"GET","POST"})
     */
    public function apiGetTasks(TaskRepository $repository, Request $request,AnnounceService $announceService)
    {
        switch ($request->getMethod()) {
            case "POST":
                $user = $this->needToBeUser();
                $data = $this->getRequestData();
                $this->is->isCategory($data["cat1"]);
                $this->is->isCategory($data["cat2"]);
                $this->is->isString($data["callBefore"]);
                $this->is->isUserAddress($data["address"]);
                $this->is->isUserContact($data["contact"]);
                $this->is->isArray($data["pics"]);

                //计算值
                $data["createAt"] = new \datetime();
                $data["createAt"] = $data["createAt"]->format('c');
                $data["expireAt"] = new \datetime("+" . $data["expireAt"] . " days");
                $data["expireAt"] = $data["expireAt"]->format('c');

                /**@var $Task Task */
                $Task = $this->createEntity($data, Task::class);
                $Task->setSn($this->createOrderSn())
                    ->setStatus(0)
                    ->setType(1)
                    ->setUser($user);
                $this->myEm()->persist($Task);
                $this->myEm()->flush();

                //发布通知
                $announceService->dealWithTaskCreate($Task);

                return $this->json_out(200, "创建成功", $Task);
            default:
                if (!$page = $this->getParamRequired("page")) {
                    $page = 1;
                }
                $limit = 10;
                $offset = (int)abs($limit * ($page - 1));
                $total = $repository->count([]);
                $this->setMeta($page, $total, $limit);
                $list = $repository->findBy(array(), array(), $limit, $offset);
                return $this->json_out(200, "获取成功", $list);
        }
    }

    /**
     * @Route("/api/tasks/{id}", name="apiAddTasks",methods={"GET","PUT","PATCH","DELETE"})
     */
    public function apiUpdateTasks(Task $Task, Request $request)
    {
        $data = $this->getRequestData();
        switch ($request->getMethod()) {
            case "DELETE":
                $this->myEm()->remove($Task);
                $this->myEm()->flush();
                return $this->json_out(200, "已移除");
            case "PATCH":
            case "PUT":
                /**@var $Task Task */
                $Task = $this->updateEntity($data, Task::class, $Task);
                break;
            case "Get":
            default:
        }
        $this->myEm()->persist($Task);
        $this->myEm()->flush();
        return $this->json_out(200, "获取成功", $Task);
    }


    /**
     * @Route("/api/task/{id}/cancel", name="apiTaskCancel",methods={"GET","PUT","PATCH","DELETE"})
     */
    public function apiTaskCancel(Task $task)
    {
        $data = $this->getRequestData();
        $user = $this->needToBeUser();
        if ($task->getUser() != $user) {
            return $this->json_out(400,"权限不足");
        }
        if ($task->getStatus() > 0) {
            return $this->json_out(400,"任务已超过取消期限");
        }
        $this->myEm()->remove($task);
        $this->myEm()->flush();
        return $this->json_out(200,"删除成功",$data);
    }


    /**
     * @Route("/api/task/{id}/confirm", name="apiTaskConfirm",methods={"GET","PUT","PATCH","DELETE"})
     */
    public function apiTaskConfirm(Task $task)
    {
        if (!$content = $this->getParamRequired("content")) {
            $content = "用户没有做出评价";
//            return $this->json_out(400,"请输入评价内容");
        }
        if (!$score = $this->getParamRequired("score")) {
            $score = 5;
//            return $this->json_out(400,"请输入评价内容");
        }
        $data = $this->getRequestData();
        $user = $this->needToBeUser();
        if ($task->getUser() != $user) {
            return $this->json_out(400,"权限不足");
        }
        if ($task->getStatus() >= 900) {
            return $this->json_out(400,"任务已确认");
        }

        //修改任务状态
        $task->setStatus(900)
            ->setConfirmAt(new \DateTime())
            ->setFinishAt(new \DateTime());

        //修改订单状态
        $orders = $task->getOrders();
        $orders->setStatus(300);

        //保存评价信息
        $comment = new Comment();
        $comment->setWho($user)->setWhat($orders)->setCreateAt(new \DateTime())->setContent($content)->setScore($score);

        $this->myEm()->flush();
        return $this->json_out(200,"确认成功",$data);
    }



    /**
     * @Route("/api/task/get/all", name="apiTaskGetAll",methods={"GET","PUT","PATCH","DELETE"})
     */
    public function apiTaskGetAll(TaskRepository $repository)
    {

        if (!$page = $this->getParamRequired("page")) {$page = 1;}
        $qb = $repository->createQueryBuilder("A");
        $qb->select("A")
            ->join("App:UserAddress","B","with","A.address = B");
        $qb->where("A.type = 1");
        $qb->orderBy("A.createAt","DESC");
        $qb->setMaxResults(10);
        $qb->setFirstResult($page * 10 -10);
        $data = $qb->getQuery()->execute();

        $this->setGroups("task");
        return $this->json_out(200,"ok",$data);
    }
}
